package com.rock.code.common.util;

/**
 * @author zhangli
 * @version V1.0
 * @create 2019-02-20 18:51
 **/

import javax.servlet.ServletContext;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public final class SpringContext {
    private static BeanFactory springBeanFactory = null;

    public SpringContext() {
    }

    public static synchronized boolean initialize(ServletContext servletContext) {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        springBeanFactory = context;
        System.out.println("SpringContext initialized!");
        return true;
    }

    public static Object getBean(String beanName) {
        Object object = null;
        if (springBeanFactory == null) {
            throw new RuntimeException("没有初始化BeanFactory！");
        } else {
            object = springBeanFactory.getBean(beanName);
            return object;
        }
    }

    public static void setBeanFactory(BeanFactory beanFactory) {
        springBeanFactory = beanFactory;
    }
}
